Setting up basic plots

This shows how you can go from a dataframe to a plot, to an app.

You can open and run this entire notebook in Colab; this allows you to prototype and test code for use in a single-page Dash app without ever leaving your Colab/Jupyter notebook environment.

Open In Colab

!pip install dash
from dash import Dash, html, dcc, callback, Output, Input
import plotly.express as px
import pandas as pd
import plotly.graph_objects as go

quakes = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv')
/bin/bash: line 1: pip: command not found

We can check the content of the dataframe, and see what the titles of the columns are:

quakes.columns
Index(['Date', 'Latitude', 'Longitude', 'Magnitude'], dtype='object')

We can plot the data using the plotly library, using the Density map function:

fig = go.Figure(go.Densitymap(lat=quakes.Latitude, lon=quakes.Longitude, z=quakes.Magnitude,
                                 radius=10))
fig.update_layout(map_style="open-street-map", map_center_lon=180)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

If we want to add in selectors for the data, we need to convert it to an app:

# What do we want to be able to select for:

quakes.Magnitude.unique()
array([6.  , 5.8 , 6.2 , 6.7 , 5.9 , 8.2 , 5.5 , 5.6 , 6.1 , 8.7 , 5.7 ,
       7.3 , 6.5 , 6.4 , 6.3 , 7.  , 7.4 , 7.6 , 6.8 , 7.7 , 7.2 , 7.8 ,
       6.9 , 6.6 , 7.5 , 7.1 , 6.35, 8.1 , 5.62, 5.63, 7.9 , 5.52, 5.82,
       5.54, 8.  , 5.64, 5.55, 5.67, 5.84, 5.81, 6.47, 6.31, 5.75, 5.66,
       5.51, 6.45, 6.57, 5.77, 5.53, 5.69, 5.89, 5.58, 8.3 , 5.94, 8.4 ,
       6.48, 5.97, 9.1 , 8.6 , 5.88, 8.8 , 5.72, 6.02, 5.73])
app = Dash()

app.layout = [
    html.H1(children='Title of Dash App', style={'textAlign':'center'}),
    dcc.Dropdown(quakes.Magnitude.unique(), 5.5, id='dropdown-selection'),
    dcc.Graph(id='graph-content')
]

@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
def update_graph(value):
    df = quakes[quakes.Magnitude==value]
    fig = go.Figure(go.Densitymap(lat=df.Latitude, lon=df.Longitude, z=df.Magnitude,
                                 radius=10))
    fig.update_layout(map_style="open-street-map", map_center_lon=180)
    fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
    fig.update_traces(showscale=False)
    return fig

if __name__ == '__main__':
    app.run(debug=True)